package com.hoyin.lightctrl_esp8266;

import android.content.Context;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class LocalConfigIO {
	private File cfgFile = null;
	private Context context;
	private String filename = null;

	public LocalConfigIO(Context context) {
		this.context = context;
	}

	public String ReadConfig() {
		FileInputStream fis = null;
		try {
			fis = context.openFileInput(cfgFile.getName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		InputStreamReader inputStreamReader = new InputStreamReader(fis, StandardCharsets.UTF_8);
		StringBuilder stringBuilder = new StringBuilder();
		try (BufferedReader reader = new BufferedReader(inputStreamReader)){
			String line = reader.readLine();
			while (line != null) {
				stringBuilder.append(line).append('\n');
				line = reader.readLine();
			}
		} catch (Exception e) {

		} finally {
			String contents = stringBuilder.toString();
			return contents;
		}
	}

	public JsonConfig ReadJsonConfig() {
		ObjectMapper om = new ObjectMapper();
		JsonConfig jsonConfig = new JsonConfig();
		try {
			jsonConfig = om.readValue(cfgFile, JsonConfig.class);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			return jsonConfig;
		}
	}

	public void WriteConfig(String contents) {
		try {
			FileOutputStream fos = context.openFileOutput(cfgFile.getName(), Context.MODE_PRIVATE);
			fos.write(contents.getBytes());
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public void WriteJsonConfig(JsonConfig config) {
		ObjectMapper om = new ObjectMapper();
		byte[] jsonConfig;
		try {
			FileOutputStream fos = context.openFileOutput(cfgFile.getName(), Context.MODE_PRIVATE);
			jsonConfig = om.writeValueAsBytes(config);
			fos.write(jsonConfig);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean IsConfigExist() {
		return cfgFile.exists();
	}

	public boolean CreateConfigFile() {
		if (IsConfigExist()) return false;
		cfgFile = new File(context.getFilesDir(), filename);
		try {
			cfgFile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	public void AttachFile(String filename) {
		cfgFile = new File(context.getFilesDir(), filename);
		this.filename = cfgFile.getName();
	}

	public String GetName() {
		return cfgFile.getName();
	}

	public String GetPath() {
		return cfgFile.getAbsolutePath();
	}
}
